//
//  UserManager.m
//  WorldOfFacts_V2
//
//  Created by Demjanko Denis on 17.11.12.
//  Copyright (c) 2012 it-dimension. All rights reserved.
//

#import "UserManager.h"

@implementation UserManager

#pragma mark - init

@synthesize name,ava,auth;

+(UserManager*)currentUser{
    __strong static UserManager* _currentUser = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _currentUser = [[UserManager alloc]init];
    });
    return _currentUser;
}

-(id)init{
    self = [super init];
        
    if([[NSUserDefaults standardUserDefaults]objectForKey:@"user_ava"] && [[NSUserDefaults standardUserDefaults]objectForKey:@"user_name"]){
        self.ava = [NSURL URLWithString:[[NSUserDefaults standardUserDefaults]objectForKey:@"user_ava"]];
        self.name = [NSString stringWithString:[[NSUserDefaults standardUserDefaults]objectForKey:@"user_name"]];
        self.auth = [[[NSUserDefaults standardUserDefaults]objectForKey:@"auth"] intValue];
    }

    return self;
}

-(void)setUser:(NSDictionary*)userInfo{    
    if([userInfo valueForKey:@"name"])
        self.name = [NSString stringWithFormat:@"%@",[userInfo valueForKey:@"name"]];
    else
        self.name = [NSString stringWithFormat:@"%@ %@",[userInfo valueForKey:@"first_name"],[userInfo valueForKey:@"last_name"]];
    
    NSString *ava_str = nil;
    
    if([userInfo valueForKey:@"photo_big"])
        ava_str = [userInfo valueForKey:@"photo_big"];
    else if([userInfo valueForKey:@"profile_image_url"])
        ava_str = [[userInfo valueForKey:@"profile_image_url"] stringByReplacingOccurrencesOfString:@"bigger" withString:@"normal"];
    else
        ava_str = [NSString stringWithFormat:@"https://graph.facebook.com/%@/picture?type=large",[userInfo valueForKey:@"username"]];
    
    self.ava = [NSURL URLWithString:ava_str];
    self.auth = [[userInfo objectForKey:@"auth"] intValue];

    [[NSUserDefaults standardUserDefaults] setObject:self.name forKey:@"user_name"];
    [[NSUserDefaults standardUserDefaults] setObject:ava_str forKey:@"user_ava"];
    [[NSUserDefaults standardUserDefaults] setObject:[userInfo objectForKey:@"auth"] forKey:@"auth"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

@end
